package com.nc.user.controller;

import com.google.common.collect.Lists;
import com.nc.user.dao.FrmUsersDao;
import com.nc.user.model.dto.UserDto;
import com.nc.user.model.entity.FrmRole;
import com.nc.user.model.entity.FrmUsers;
import com.nc.user.service.AdminUsersService;
import com.nc.user.service.PermissionsService;
import com.nc.user.service.UserService;
import com.plug.result.RetResponse;
import com.plug.result.RetResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.mgt.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.UserDataHandler;

import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@RestController
@RequestMapping("UsersController")
@Api(tags = "用户接口")
public class UsersController {
    @Autowired
    SessionManager sessionManager;
    @Autowired
    UserService userService;
    @Autowired
    AdminUsersService adminUsersService;
    @Autowired
    PermissionsService permissionsService;
    @Autowired
    FrmUsersDao frmUsersDao;

    @ApiOperation("根据token获得当前登录人")
    @GetMapping("user/{token}")
    public RetResult getUserByToken(@PathVariable("token") String token) {
        FrmUsers fspuser = (FrmUsers) SecurityUtils.getSubject().getSession().getAttribute("Users");
        return RetResponse.makeOKRsp(fspuser);
    }

    @ApiOperation("根据token获得所有角色和权限")
    @GetMapping("permissions/{token}")
    public RetResult getByToken(@PathVariable("token") String token) {
        FrmUsers fspuser = (FrmUsers) SecurityUtils.getSubject().getSession().getAttribute("Users");
        JSONObject ret = new JSONObject();
        ret.put("role", fspuser.getFrmRoles());
        ret.put("permissions", permissionsService.findByRoles(Lists.newArrayList(fspuser.getFrmRoles().stream().collect(Collectors.groupingBy(FrmRole::getCode)).keySet())));
        return RetResponse.makeOKRsp(ret);
    }

    @ApiOperation("修改当前登录人密码")
    @PutMapping("user")
    public RetResult updatePassword(String psd, String npsd) {
        return userService.updatePassword(psd, npsd);
    }

    @ApiOperation("保存")
    @PostMapping("save")
    public RetResult addData(@RequestBody UserDto userDto) {
        FrmUsers fspuser = (FrmUsers) SecurityUtils.getSubject().getSession().getAttribute("Users");
        userDto.setId(fspuser.getId());
        return adminUsersService.save(userDto);
    }

    @ApiOperation("根据用户id获得用户信息")
    @GetMapping("user/details/{userId}")
    public RetResult userDetail(@PathVariable String userId) {
        return RetResponse.makeOKRsp(frmUsersDao.findById(userId).get());
    }
}
